package auth

import (
	"beegoProject10/models/auth"
	"beegoProject10/utils"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"math"
	"time"
)

type AuthController struct {
	beego.Controller
}

func (c *AuthController) List() {

	// 1 初始化数据库
	o := orm.NewOrm()
	qs := o.QueryTable("sys_auth")

	// 2 每夜显示到条数 -> pagePerNum
	pagePerNum := 5

	// 3 当前页 -> currentPage
	currentPage, err := c.GetInt("page")
	if err != nil {
		currentPage = 1
	}

	// 4 数据总量 -> count
	count, _ := qs.Filter("is_delete", 0).Count()

	// 5 总页数 -> countPage
	countPage := int(math.Ceil(float64(count) / float64(pagePerNum)))

	pageMap := utils.Paginator(currentPage, pagePerNum, count)

	// 7 数据查询
	auths := []auth.Auth{}
	qs.Filter("is_delete", 0).All(&auths)

	// 8 (下一页)当前页数小于总页数，下一页可以+1
	nextPage := 1
	if currentPage < countPage {
		nextPage = currentPage + 1
	} else if currentPage >= countPage { // 最后页就不能+1
		nextPage = currentPage
	}

	// (上一页)当前页面=1，不能-1
	prePage := 1
	if currentPage == 1 {
		prePage = currentPage
	} else if currentPage > 1 {
		prePage = currentPage - 1
	}

	// 6 传入前端
	c.Data["pageMap"] = pageMap
	c.Data["countPage"] = countPage
	c.Data["count"] = count
	c.Data["auths"] = auths

	// 9 前端分页
	c.Data["currentPage"] = currentPage
	c.Data["nextPage"] = nextPage
	c.Data["prePage"] = prePage

	c.TplName = "auth/auth-list.html"
}

func (c *AuthController) ToAdd() {

	// 1 初始化模型
	auths := []auth.Auth{}

	// 2 数据库
	o := orm.NewOrm()
	qs := o.QueryTable("sys_auth")

	// 3 查询
	qs.Filter("is_delete", 0).All(&auths)

	// 4 显示
	c.Data["auths"] = auths
	fmt.Println(auths)

	c.TplName = "auth/auth-add.html"
}

func (c *AuthController) DoAdd() {

	//  1.获取数据
	authParentId, _ := c.GetInt("auth_parent_id")
	authName := c.GetString("auth_name")
	authUrl := c.GetString("auth_url")
	authDesc := c.GetString("auth_desc")
	isActive, _ := c.GetInt("is_active")
	authWeight, _ := c.GetInt("auth_weight")

	// 2. 初始化数据，按照顺序
	authDate := auth.Auth{
		AuthName:   authName,
		UrlFor:     authUrl,
		Pid:        authParentId,
		Desc:       authDesc,
		CreateTime: time.Now(),
		IsActive:   isActive,
		Weight:     authWeight,
	}

	// 3. 存入数据库
	o := orm.NewOrm()
	id, err := o.Insert(&authDate)
	fmt.Println("ID: =========", id)
	fmt.Println(err)

	// 4. 前端json显示
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "添加成功",
	}
	c.ServeJSON()
}
